package com.zzb.servlet.user;



import com.alibaba.fastjson.JSONObject;
import com.zzb.DTO.ResultDTO;
import com.zzb.VO.UserVO;
import com.zzb.service.UserService;
import com.zzb.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.乱码处理
        req.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        resp.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        //2.得到前端值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String sessionCode = (String) req.getSession().getAttribute("vCode");
        //3.将前端值封装
        UserVO userVO = UserVO.builder()
                .username(username)
                .password(password)
                .code(code)
                .sessionCode(sessionCode)
                .build();
        //4.逻辑处理
        UserService userService = new UserServiceImpl();
        //5.得到处理结果
        ResultDTO resultDTO = userService.login(userVO);
        if ("success".equals(resultDTO.getMsg())) {
            req.getSession().setAttribute("username", username);
        }
        //6.响应数据到前端
        resp.getWriter().println(JSONObject.toJSONString(resultDTO));
    }
}
